const {
    addCommentServe,
    getCommentByUserIdServe,
    getCommentListServe,
    deleteCommentServe
} = require('../serve/comment.serve')
const {getBikeByIdServe} = require("../serve/bike.serve")
let that

class CommentController {
    constructor() {
        that = this
    }

    async addComment(ctx) {
        try {
            const {content, bikeId, img} = ctx.request.body
            const {id: createdUserId, nickName: createdUserName, avatar} = ctx.state.appletUser
            const bike = await getBikeByIdServe(bikeId)
            let bikeName = bike.brandName + bike.name
            let source = ctx.request.url.includes('wx') ? 'weixin' : 'zfb'
            await addCommentServe({content, bikeId, img, createdUserId, createdUserName, avatar, bikeName, source})
            ctx.body = {
                msg: '添加成功',
                status: 0
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async getCommentList(ctx) {
        try {
            const res = await getCommentListServe(ctx)
            ctx.body = {
                msg: '获取成功',
                status: 0,
                data: {
                    total: res.total,
                    pageSize: Number(res.pageSize),
                    pageNum: Number(res.pageNum),
                    pageData: res.data
                }
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async deleteCommentFunction(ctx, id, isApplet) {
        try {
            if (isApplet) {
                let {id: createdUserId} = ctx.state.appletUser
                const res = await getCommentByUserIdServe({id, createdUserId});
                if (!res) {
                    console.log('未找到id或者userId对应的数据')
                    throw ({message: '删除失败'})
                }
            } else {
                const res = await getCommentByUserIdServe({id});
                if (!res) {
                    console.log('未找到id或者userId对应的数据')
                    throw ({message: '删除失败'})
                }
            }
            const isSuccessDelete = await deleteCommentServe(id);
            ctx.body = {
                msg: '删除成功',
                status: 0,
                data: isSuccessDelete
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async deleteComment(ctx) {
        const {id} = ctx.params;
        await that.deleteCommentFunction(ctx, id, false)
    }

    async deleteAppletComment(ctx) {
        const {id} = ctx.params;
        await that.deleteCommentFunction(ctx, id, true)
    }
}

module.exports = new CommentController()
